<template>
  <div class="register" :class="{ backActive: !props.imgChange }">
    <h2>注册</h2>
    <el-steps
      :active="stepActive"
      finish-status="success"
      style="width: 300px; margin: 20px 0"
      align-center
    >
      <el-step title="基础信息" />
      <el-step title="邮箱验证" />
    </el-steps>
    <div class="input-group">
      <div class="inputMoveContainer" ref="moveContainer">
        <div class="items">
          <el-form ref="baseForm" :rules="registerRules" :model="baseInfo">
            <el-form-item class="form-item" prop="userName">
              <i class="fa fa-user-o icon"></i>
              <div class="inputBox">
                <el-input
                  type="text"
                  v-model="baseInfo.userName"
                  class="input"
                  placeholder="请输入昵称"
                />
              </div>
            </el-form-item>
            <el-form-item class="form-item" prop="password">
              <i class="fa fa-key icon"></i>
              <div class="inputBox">
                <el-input
                  type="password"
                  class="input"
                  v-model="baseInfo.password"
                  placeholder="请输入密码"
                />
              </div>
            </el-form-item>
            <el-form-item class="form-item" prop="judgePassword">
              <i class="fa fa-key icon"></i>
              <div class="inputBox">
                <el-input
                  class="input"
                  type="password"
                  v-model="baseInfo.judgePassword"
                  placeholder="请再次输入密码"
                />
              </div>
            </el-form-item>
          </el-form>
        </div>
        <div class="items">
          <el-form ref="emailForm" :rules="registerRulesE" :model="emailInfo">
            <el-form-item class="form-item" prop="email">
              <i class="fa fa-envelope-o icon"></i>
              <div class="inputBox">
                <el-input
                  class="input"
                  v-model="emailInfo.email"
                  placeholder="请输入邮箱"
                />
              </div>
            </el-form-item>
            <el-form-item class="form-item" prop="code">
              <div class="codeBox">
                <i class="fa fa-paperclip icon"></i>
                <div style="width: 120px">
                  <el-input
                    class="codeInput"
                    v-model="emailInfo.code"
                    placeholder="请输入验证码"
                  />
                </div>
              </div>
              <el-button
                class="codeBtn"
                @click="handleCodeClick"
                :disabled="code.isLock"
                >{{ code.codeMessage }}</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <div class="btnContainer" v-if="stepActive">
      <el-button class="btn small" @click="preStep">上一步</el-button>
      <el-button class="btn small" @click="handleRegisterClick(emailForm)"
        >完成</el-button
      >
    </div>
    <el-button v-else class="btn" @click="nextStep(baseForm)">下一步</el-button>
  </div>
</template>

<script setup>
import { defineProps, reactive, ref, watch } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElNotification } from "element-plus";
import { sendEmailCode } from "@/service/user";
import Cache from "@/utils/Cache";
const router = useRouter();
const moveContainer = ref();
let stepActive = ref(0);
const baseForm = ref();
const emailForm = ref();
const code = reactive({
  codeMessage: "获取验证码",
  codeSecond: 10,
  isLock: false,
});
const props = defineProps({
  imgChange: {
    type: Boolean,
    required: true,
  },
});

// 基础信息
const baseInfo = reactive({
  userName: "",
  password: "",
  judgePassword: "",
});

// 邮箱信息
const emailInfo = reactive({
  email: "",
  code: "",
});

// 初始化操作，展示baseForm
watch(props, (newValue) => {
  if (!newValue.imgChange) {
    moveContainer.value.style.left = "0";
    stepActive.value = 0;
  }
});

// 基本信息=>邮箱验证
const nextStep = async (baseForm) => {
  await baseForm.validate((valid) => {
    if (!valid) {
      ElMessage({
        message: "输入信息不完整！",
        type: "warning",
        center: true,
      });
      return;
    }
    if (!judgeUserIsExisted(baseInfo.userName, 1)) {
      ElMessage({ message: "该昵称已存在！", type: "warning", center: true });
      return;
    }
    moveContainer.value.style.left = "-300px";
    stepActive.value = 1;
  });
};

// 邮箱验证=>基础信息
const preStep = () => {
  moveContainer.value.style.left = "0";
  stepActive.value = 0;
};

// 获取验证码逻辑处理
const handleCodeClick = async () => {
  if (!testDataisEmail(emailInfo.email)) {
    ElMessage({ message: "邮箱格式不正确！", type: "warning", center: true });
    return;
  }
  code.isLock = true;
  try {
    let timer = setInterval(() => {
      code.codeMessage = `${code.codeSecond}s后重新获取`;
      if (code.codeSecond === 0) {
        clearInterval(timer);
        code.codeMessage = `获取验证码`;
        code.codeSecond = 10;
        code.isLock = false;
        return;
      }
      code.codeSecond--;
    }, 1000);
    await sendEmailCode({ email: emailInfo.email });
    ElMessage({
      message: "已发送验证码，请查看邮箱！",
      type: "success",
      center: true,
    });
  } catch (err) {
    ElMessage({
      message: "发送失败！",
      type: "warning",
      center: true,
    });
    code.isLock = false;
    return;
  }
};

// 注册按钮逻辑
const handleRegisterClick = async (emailForm) => {
  await emailForm.validate((valid) => {
    if (valid) {
      if (!judgeUserIsExisted(emailInfo.email, 2)) {
        ElMessage({
          message: "该邮箱已被注册！",
          type: "warning",
          center: true,
        });
        return;
      }
      saveUserInfo();
    } else {
      ElMessage({
        message: "输入信息不完整！",
        type: "warning",
        center: true,
      });
    }
  });
};

// 将注册信息保存至本地
const saveUserInfo = () => {
  const info = {};
  info.name = baseInfo.userName;
  info.password = baseInfo.password;
  info.email = emailInfo.email;
  info.code = emailInfo.code;
  //保存用户信息至本地
  Cache.saveItem("user", {
    nickName: info.name,
    email: info.email,
    password: info.password,
    avatar: 0,
    sex: 0,
    introduce: "",
    fav: [0, 0, 0, 0, 0, 0, 0, 0],
    createTime: Date.now(),
  });
  ElNotification({
    title: "注册成功！",
    message: "即将跳转至个人页面！",
    type: "warning",
  });
  setTimeout(() => {
    router.push("/my");
  }, 2000);
};

// 判断本地缓存的用户信息是否和注册信息重复
const judgeUserIsExisted = (params, type) => {
  if (!Cache.getItem("user")) {
    return true;
  }
  const user = Cache.getItem("user");
  return type === 1 ? user.nickName !== params : user.email !== params;
};

// 判断用户输入是否为邮箱
const testDataisEmail = (info) => {
  const rep = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(com|cn|net)$/;
  return rep.test(info);
};

// 自定义校验规则，前后密码一致
const validatePass = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请再次输入密码！"));
  } else if (value !== baseInfo.password) {
    callback(new Error("两次密码不一致！"));
  } else {
    callback();
  }
};

// 注册表单验证（基础信息）
const registerRules = reactive({
  userName: [
    {
      required: true,
      message: "请输入昵称！",
      trigger: "blur",
    },
    { min: 3, message: "用户名长度不符！", trigger: "blur" },
  ],
  password: [
    {
      required: true,
      message: "请输入密码！",
      trigger: "blur",
    },
    { min: 5, message: "密码长度不少于5位！", trigger: "blur" },
  ],
  judgePassword: [
    { min: 5, message: "密码长度不少于5位！", trigger: "blur" },
    { validator: validatePass, trigger: "blur" },
  ],
});

// 注册表单验证（邮箱验证）
const registerRulesE = {
  email: [
    {
      required: true,
      message: "请输入邮箱！",
      trigger: "blur",
    },
    {
      pattern:
        /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(com|cn|net)$/,
      message: "邮箱格式不符！",
      trigger: "blur",
    },
  ],
  code: [
    {
      required: true,
      message: "请输入验证码！",
      trigger: "blur",
    },
    {
      pattern: /^\d{6}$/,
      message: "验证码长度为6个字符",
      trigger: "blur",
    },
  ],
};
</script>

<style scoped lang="less">
.backActive {
  transform: rotateY(0deg) !important;
}
/deep/.el-step__title.is-success {
  color: #71df3b;
}
.register {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: absolute;
  top: 0;
  width: 300px;
  box-sizing: content-box;
  border-radius: 10px;
  padding: 25px;
  height: 400px;
  background-color: #147e68bd;
  box-shadow: 5px 5px 10px #04836e, -5px -5px 10px #04836e;
  transform: rotateY(-180deg);
  backface-visibility: hidden;
  transition: 0.7s;
  h2 {
    font-size: 40px;
    font-weight: 500;
    letter-spacing: 20px;
    margin: 0;
  }
  .input-group {
    position: relative;
    width: 300px;
    height: 220px;
    overflow: hidden;
    .inputMoveContainer {
      position: absolute;
      left: 0;
      width: 900px;
      height: 210px;
      display: flex;
      transition: all 0.5s;
    }
    .items {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      margin-right: 10px;
      .inputBox {
        width: 250px;
      }
      .form-item {
        margin-bottom: 25px;
      }
      .input /deep/ .el-input__wrapper {
        background-color: #fff;
        border-radius: 0;
        border-top-right-radius: 5px;
        border-bottom-right-radius: 5px;
        width: 250px;
        height: 40px;
        border: none;
        outline-style: none;
        padding: 5px;
      }
      /deep/ .el-form-item__error {
        margin-left: 40px;
        margin-top: 5px;
        color: rgb(250, 157, 50);
      }
      .codeBox {
        display: flex;
        .codeInput /deep/ .el-input__inner {
          border-radius: 0;
          border-top-right-radius: 5px;
          border-bottom-right-radius: 5px;
          height: 40px;
          border: none;
          outline-style: none;
          padding: 5px;
        }
      }
      .codeBtn {
        width: 120px;
        height: 40px;
        color: #fff;
        background-color: #0b493d;
        border: none;
        margin-left: 10px;
        &:hover {
          background-color: #127a66;
        }
      }
    }
    /deep/ .el-form-item__content {
      flex-wrap: nowrap;
    }

    .icon {
      border-top-left-radius: 5px;
      border-bottom-left-radius: 5px;
      display: block;
      width: 40px;
      height: 40px;
      text-align: center;
      line-height: 40px;
      color: #fff;
      background-color: #0b493d;
    }
  }
  .btnContainer {
    display: flex;
    .small {
      height: 40px;
      width: 140px;
    }
  }
  .btn {
    color: #fff;
    background-color: #0b493d;
    border: none;
    width: 290px;
    height: 40px;
  }
  .btn:hover {
    background-color: #127a66;
  }
}
</style>
